package leetcode;



import java.util.ArrayDeque;
import java.util.Queue;

/**
 * 岛屿数量
 */
public class LeetCode200 {
    public int numIslands(char[][] grid) {
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    bfs(i, j, grid);
                    count++;
                }
            }
        }
        return count;
    }

    public void bfs(int x, int y, char[][] grid) {
        grid[x][y] = '0';
        Queue<Pair> queue = new ArrayDeque<>();
        queue.offer(new Pair(x, y));
        while (!queue.isEmpty()) {
            Pair pair = queue.poll();
            x = pair.x;
            y = pair.y;
            // top
            if (x > 0 && grid[x - 1][y] == '1') {
                grid[x - 1][y] = '0';
                queue.offer(new Pair(x - 1, y));
            }
            // bottom
            if (x < grid.length - 1 && grid[x + 1][y] == '1') {
                grid[x + 1][y] = '0';
                queue.offer(new Pair(x + 1, y));
            }
            // left
            if (y > 0 && grid[x][y - 1] == '1') {
                grid[x][y - 1] = '0';
                queue.offer(new Pair(x, y - 1));
            }
            // right
            if (y < grid[0].length - 1 && grid[x][y + 1] == '1') {
                grid[x][y + 1] = '0';
                queue.offer(new Pair(x, y + 1));
            }
        }

    }

    public static class Pair {
        int x;
        int y;

        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    public static void main(String[] args) {
        LeetCode200 leetCode200 = new LeetCode200();
        char[][] grid = new char[][]{
                {'1', '0', '1'},
                {'1', '0', '1'},
                {'0', '0', '1'},
                {'1', '0', '1'},
        };
        System.out.println(leetCode200.numIslands(grid));
    }
}